package com.ruoyi.system.controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.TaskAttachment;
import com.ruoyi.system.service.ITaskAttachmentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.config.RuoYiConfig;
import java.io.File;

/**
 * 任务附件Controller
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/task/attachment")
public class TaskAttachmentController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(TaskAttachmentController.class);

    @Autowired
    private ITaskAttachmentService taskAttachmentService;

    /**
     * 查询任务附件列表
     */
    @PreAuthorize("@ss.hasPermi('task:attachment:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskAttachment taskAttachment)
    {
        startPage();
        List<TaskAttachment> list = taskAttachmentService.selectTaskAttachmentList(taskAttachment);
        return getDataTable(list);
    }

    /**
     * 查询任务的附件列表
     */
    @PreAuthorize("@ss.hasPermi('task:attachment:list')")
    @GetMapping("/listByTask/{taskId}/{taskType}")
    public AjaxResult listByTask(@PathVariable("taskId") Long taskId, @PathVariable("taskType") Integer taskType)
    {
        List<TaskAttachment> list = taskAttachmentService.selectTaskAttachmentsByTaskId(taskId, taskType);
        return AjaxResult.success(list);
    }

    /**
     * 获取任务附件详情
     */
    @PreAuthorize("@ss.hasPermi('task:attachment:query')")
    @GetMapping(value = "/{attachmentId}")
    public AjaxResult getInfo(@PathVariable("attachmentId") Long attachmentId)
    {
        return AjaxResult.success(taskAttachmentService.selectTaskAttachmentById(attachmentId));
    }

    /**
     * 上传任务附件
     */
    @PreAuthorize("@ss.hasPermi('task:attachment:add')")
    @Log(title = "任务附件", businessType = BusinessType.INSERT)
    @PostMapping("/upload")
    public AjaxResult upload(@RequestParam("taskId") Long taskId, 
                             @RequestParam("taskType") Integer taskType,
                             @RequestParam("file") MultipartFile file)
    {
        try
        {
            TaskAttachment attachment = taskAttachmentService.uploadTaskAttachment(taskId, taskType, file);
            return AjaxResult.success("上传成功", attachment);
        }
        catch (Exception e)
        {
            return AjaxResult.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 下载任务附件
     */
    @PreAuthorize("@ss.hasPermi('task:attachment:query')")
    @GetMapping("/download/{attachmentId}")
    public void download(@PathVariable("attachmentId") Long attachmentId, HttpServletResponse response) throws IOException
    {
        try 
        {
            TaskAttachment attachment = taskAttachmentService.selectTaskAttachmentById(attachmentId);
            if (attachment != null)
            {
                // 获取完文件路径
                String relativePath = attachment.getFilePath();
                String fileName = attachment.getFileName();

                if (relativePath.startsWith("/profile")) {
                    relativePath = relativePath.substring("/profile".length());
                }

                String realFilePath = RuoYiConfig.getProfile() + relativePath;
                File file = new File(realFilePath);
                
                logger.info("下载文件路径: {}, 文件是否存在: {}", realFilePath, file.exists());
                
                if (file.exists() && file.isFile())
                {
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
                    response.addHeader("Content-Length", "" + attachment.getFileSize());
                    
                    logger.info("开始下载文件: {}, 大小: {}", fileName, attachment.getFileSize());
                    FileUtils.writeBytes(realFilePath, response.getOutputStream());
                    logger.info("文件下载完成: {}", fileName);
                }

            }

        }
        catch (Exception e)
        {
            logger.error("文件下载失败，附件ID: " + attachmentId, e);
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("文件下载失败: " + e.getMessage());
        }
    }

    /**
     * 删除任务附件
     */
    @PreAuthorize("@ss.hasPermi('task:attachment:remove')")
    @Log(title = "任务附件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{attachmentIds}")
    public AjaxResult remove(@PathVariable Long[] attachmentIds)
    {
        return toAjax(taskAttachmentService.deleteTaskAttachmentByIds(attachmentIds));
    }
} 